<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/goods">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex" align-center finish-status="success" :space="200">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单内容区域 -->
      <el-form ref="editFormRef" label-width="100px" label-position="top" :model="editForm" :rules="editFormRules">
        <!-- tab标签页区域:左侧tab选线 -->
        <el-tabs v-model="activeIndex" tab-position="left" @tab-click="handleTabClick" :before-leave="beforeLeaveHandler">
          <el-tab-pane label="基本信息" :name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="editForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="editForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="editForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="editForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 选择商品分类的级联选择框 -->
              <el-cascader ref="cateHandle" v-model="selectedKeys" :options="parentCateList" :props="cascaderProps" @change="parentCateChange" clearable change-on-select></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" :name="1">
            <template v-if="manyTableData.length">
              <!-- 渲染表单的item项 -->
              <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
                <!-- 复选框组 -->
                <el-checkbox-group v-model="item.attr_vals_arr">
                  <el-checkbox :label="cb" :value="cb" v-for="(cb, i) in item.attr_vals" :key="i"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </template>
            <div v-else>暂无参数数据</div>
          </el-tab-pane>
          <el-tab-pane label="商品属性" :name="2">
            <template v-if="onlyTableData.length">
              <!-- 渲染表单的item项 -->
              <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                <!-- 下拉框组 -->
                <el-select v-if="item.attr_vals.length > 1" v-model="item.attr_vals_arr" size="large" style="width: 240px">
                  <el-option v-for="(cb, i) in item.attr_vals" :key="i" :label="cb" :value="cb" />
                </el-select>
                <el-input v-else v-model="item.attr_vals_arr"></el-input>
              </el-form-item>
            </template>
            <div v-else>暂无参数数据</div>
          </el-tab-pane>
          <el-tab-pane label="商品图片" :name="3">
            <!-- action:图片上传的后台api接口 -->
            <!-- list-type="picture":预览图片的效果 -->
            <!-- headers:添加请求头部，手动添加请求头部，保存到data中 -->
            <el-upload
              v-model:file-list="fileList"
              list-type="picture-card"
              :headers="headers"
              class="avatar-uploader"
              name="file"
              :action="`${baseURL}/upload`"
              :show-file-list="true"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemove"
              :on-preview="handlePictureCardPreview"
              :before-upload="handleBeforeUpload"
              multiple
              :on-change="handleChange"
            >
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <!-- 图片预览 -->
            <el-dialog v-model="dialogVisible">
              <img class="previewImg" w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" :name="4">
            <div style="border: 1px solid #ccc">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
              <Editor style="min-height: 500px; overflow-y: hidden" v-model="goods_introduce" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
            </div>
            <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onBeforeUnmount, shallowRef, onMounted } from 'vue'
import { getCateListApi } from '@/api/cate'
import { getAttrListApi } from '@/api/params'
import { addGoodsApi } from '@/api/goods'
import { message } from '@/utils/functions'
import { baseURL } from '@/utils/request'
import { Plus } from '@element-plus/icons-vue'
// 在线文本编辑器相关代码
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
// 从pinia中获取token
import { useUserStore } from '@/stores/user'
import { useRouter, useRoute } from 'vue-router'
const userStore = useUserStore()
const router = useRouter()
const token = userStore.token
const headers = {
  Authorization: token
}

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const goods_introduce = ref('')
// 工具栏的配置
const toolbarConfig = {}
// 编辑器的配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    // 文件上传相关的配置
    uploadImage: {
      base64LimitSize: 5 * 1024, // 5kb
      server: `${baseURL}/upload`,
      headers: {
        Authorization: token
      },
      fieldName: 'file',
      // 自定义上传
      async customUpload(file, insertFn) {
        const url = URL.createObjectURL(file)
        // 最后插入图片
        insertFn(url)
      }
    }
  }
}
// 模式
const mode = ref('simple')

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = editor => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

// 步骤条激活的索引
// tab选项卡激活的选项
const activeIndex = ref(0)
// 定义表单数据项
const editForm = ref({
  goods_name: '',
  goods_price: 0,
  goods_weight: 0,
  goods_number: 0,
  // 商品所属的分类id
  goods_cat: ''
})
//  商品的表单数据验证规则
const editFormRules = ref({
  goods_name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    {
      min: 2,
      max: 30,
      message: '商品名称的长度在2-30个字符之间',
      trigger: 'blur'
    }
  ],
  goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
  goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
  goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
  goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
})

// 级联菜单相关
// 分类数据
const parentCateList = ref([])
// 级联菜单选中项的值（每个下拉选项的value值的数组）
const selectedKeys = ref([1, 3, 6])
// 配置级联菜单中数据如何展示
const cascaderProps = ref({
  // 当要展示的下拉选项的数据的属性不是value和label时，需要配置该属性
  value: 'cat_id',
  label: 'cat_name',
  // 多级的数据的关联关系字段不是children时需要配置该属性
  children: 'children',
  // 默认情况下，级联菜单的选项是点击触发的，如果需要hover触发，需要配置该属性
  expandTrigger: 'hover',
  // 设置父子节点取消选中关联，从而达到选择任意一级选项的目的
  checkStrictly: true
})

// 获取所有分类数据
const getparentCateList = async () => {
  const data = await getCateListApi({ type: 3 })
  parentCateList.value = data
}
getparentCateList()
// 组件对象
const cateHandle = ref(null)
const parentCateChange = () => {
  if (selectedKeys.value === undefined) {
    // 分类id变成空字符串
    editForm.value.goods_cat = ''
    return
  }
  // 只允许选择三级分类作为参数所属的分类
  if (selectedKeys.value.length !== 3) {
    // 清空选中项
    selectedKeys.value = []
    // 分类id变成空字符串
    editForm.value.goods_cat = ''
    // 选中了父级后，让级联菜单隐藏
    cateHandle.value.togglePopperVisible(false)
    return
  }
  // 选中了父级后
  // 将选中的三级分类的id拼接成字符串
  editForm.value.goods_cat = selectedKeys.value.join(',')
  // 让级联菜单隐藏
  cateHandle.value.togglePopperVisible(false)
}

// 分类id
const cat_id = computed(() => {
  if (selectedKeys.value === undefined) {
    return ''
  }
  return selectedKeys.value.length ? selectedKeys.value[selectedKeys.value.length - 1] : ''
})

// 动态参数数据
const manyTableData = ref([])
// 获取静态参数数据
const onlyTableData = ref([])
// 根据分类id和类型获取参数数据
const getParamsData = async (cat_id, type) => {
  // 获取动态参数数据
  if (type === 'many') {
    const data = await getAttrListApi(cat_id, 'many')
    // 处理数据
    data.forEach(item => {
      // attr_vals是字符串，需要转换为数组
      item.attr_vals = item.attr_vals.split(',')
      // 用来收集复选框组选中的值
      item.attr_vals_arr = []
    })
    manyTableData.value = data
  } else {
    // 获取静态参数数据
    const data = await getAttrListApi(cat_id, 'only')
    // 处理数据
    data.forEach(item => {
      // attr_vals是字符串，需要转换为数组
      item.attr_vals = item.attr_vals.split(',')
      if (item.attr_vals.length === 1) {
        item.attr_vals_arr = item.attr_vals[0]
      } else {
        item.attr_vals_arr = item.attr_vals[0]
      }
    })
    onlyTableData.value = data
  }
}

// 切换选项卡时触发的事件
const handleTabClick = async tab => {
  if (activeIndex.value === 1) {
    await getParamsData(cat_id.value, 'many')
  } else if (activeIndex.value === 2) {
    await getParamsData(cat_id.value, 'only')
  }
}

// tabs切换控制
const beforeLeaveHandler = (activeName, old) => {
  if (activeName !== 0 && cat_id.value === '') {
    message('error', '请先选择三级分类菜单')
    return false
  }
  // 更改选项卡的索引
  activeIndex.value = activeName
  return true
}

// 上传图片

// 最终存储图片的数据
const fileList = ref([])

const handleAvatarSuccess = (response, uploadFile, uploadFiles) => {
  if (response.meta.status === 200) {
    // 因为每次只上传一张图片，先置空原数组
    // fileList.value.length = 0
    // 添加图片数据
    fileList.value = uploadFiles.map(item => {
      return {
        name: item.name,
        tmp: item.response.data.tmp_path,
        url: item.response.data.url
      }
    })
  }
}
// 图片预览
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 图片删除的处理
const handleRemove = (uploadFile, uploadFiles) => {
  // 多张图片，就删除当前要删除的这张
  fileList.value = uploadFiles.map(item => {
    return {
      name: item.name,
      tmp: item.tmp_path,
      url: item.url
    }
  })
}
// 图片预览
const handlePictureCardPreview = file => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 图片上传前的验证
const handleBeforeUpload = file => {
  // 定义上传文件的类型只能是图片格式
  const allowMineType = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
  // 定义图片大小不能超过2M
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!allowMineType.includes(file.type)) {
    message('error', '只能上传图片格式文件!')
    return false
  }
  if (!isLt2M) {
    message('error', '上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}
const handleChange = () => {
  // fileList.value = []
}

// 商品的添加
const addGoods = async () => {
  // 定义一个新的对象来收集接口需要的数据
  // 一部分基本数据来自于表单数据对象，可以实现拷贝
  const formData = Object.assign({}, editForm.value)
  // 获取图片地址
  formData.pics = fileList.value.map(item => ({
    pic: item.tmp
  }))
  // 获取动态参数数据
  formData.attrs = []
  manyTableData.value.forEach(item => {
    // 收集复选框选中的数据
    item.attr_vals_arr.forEach(val => {
      formData.attrs.push({
        attr_id: item.attr_id,
        attr_value: val
      })
    })
  })
  // 获取静态参数数据
  onlyTableData.value.forEach(item => {
    formData.attrs.push({
      attr_id: item.attr_id,
      attr_value: item.attr_vals_arr
    })
  })
  // 在线文本编辑器的内容
  formData.goods_introduce = goods_introduce.value
  // 添加商品
  await addGoodsApi(formData)
  message('success', '添加商品成功')
  activeIndex.value = 5
  router.push('/goods')
}
</script>

<style lang="scss" scoped>
// 图片上传区域配置
.avatar-uploader {
  :deep(.el-upload) {
    margin: 0 50px;
    width: 148px;
    height: 148px;
    .el-upload-dragger {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      text-align: center;
    }
  }
}
// 图片预览，图片大小
.previewImg {
  width: 100%;
  height: 100%;
}
// wangEditor 编辑器配置
:deep(.w-e-text-container) {
  .w-e-scroll {
    height: 500px;
  }
}

// 商品添加按钮样式
.btnAdd {
  margin-top: 15px;
}
</style>